package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"

	"github.com/gorilla/mux"
)

type User struct {
	ID    int    `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

var users []User

func init() {
	for i := 1; i <= 100; i++ {
		users = append(users, User{
			ID:    i,
			Name:  fmt.Sprintf("User %d", i),
			Email: fmt.Sprintf("user%d@example.com", i),
		})
	}
}

func getDataHandler(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	pageStr := params.Get("page")
	limitStr := params.Get("limit")

	page, err := strconv.Atoi(pageStr)
	if err != nil || page < 1 {
		http.Error(w, "Invalid page number", http.StatusBadRequest)
		return
	}

	limit, err := strconv.Atoi(limitStr)
	if err != nil || limit < 1 {
		http.Error(w, "Invalid limit", http.StatusBadRequest)
		return
	}

	start := (page - 1) * limit
	end := start + limit
	if end > len(users) {
		end = len(users)
	}

	data := map[string]interface{}{
		"data":      users[start:end],
		"totalPages": (len(users) + limit - 1) / limit,
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(data)
}

func main() {
	r := mux.NewRouter()

	r.HandleFunc("/api/data", getDataHandler).Methods("GET")

	fs := http.FileServer(http.Dir("./static"))
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "./static/index.html")
	})

	fmt.Println("Server is running on port 8080...")
	http.ListenAndServe(":8080", r)
}




